package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.SetmealDish;
import com.itheima.commons.R;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Tang
 * @date 2023/1/9
 */
@Slf4j
@RequestMapping("/dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品包含口味信息
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto) {
        //1.调用service新增方法
        dishService.addDishWithFlavor(dishDto);
        //2.返回结果
        return R.success("新增成功！");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> findPage(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  String name) {
        //0.添加分页拦截器【第一次做分页一定要添加】
        //1.创建分页对象传入page=1&pageSize=10
        Page<Dish> dishPage = new Page<>(page, pageSize);

        //2.构造查询条件 name
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Dish::getName, name);

        //3.调用service的分页接口，将分页对象以及查询对象传递给分页接口
        dishService.page(dishPage, wrapper);

        //优化================================================================
        //1.new Page<DishDto>对象
        Page<DishDto> dishDtoPage = new Page<>();

        //2.将Page<Dish>中的所有属性拷贝给Page<DishDto>，排除records属性
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        //3.需要设置records属性【List<DishDto>】到Page<DishDto>
        List<Dish> dishList = dishPage.getRecords();

        //4.List<DishDto>数据的封装：
        List<DishDto> dishDtos = new ArrayList<>();
        //4.1 循环遍历List<Dish>
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //4.2 将dish对象拷贝到 DishDto
            BeanUtils.copyProperties(dish, dishDto);
            //4.3 查询分类，根据分类id去查，得到分类对象，设置分类名称到dishDto中
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            //4.4 将dish对象添加到List<DishDto>
            dishDtos.add(dishDto);
        }
        dishDtoPage.setRecords(dishDtos);
        //5.返回Page<DishDto>
        return R.success(dishDtoPage);

        //4.返回结果给前端
        //return R.success(dishPage);
    }


    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> list(@PathVariable Long id) {
        //1.调用service的查询方法
        DishDto dishDto = dishService.getDishWithFlavor(id);
        //2.直接返回查询结果
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //1.调用service的更新方法
        dishService.updateWithFlavor(dishDto);
        //2.返回成功结果
        return R.success("修改成功！");
    }

    /**
     * 根据分类id或者菜品名称查询菜品列表
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> listBy(Dish dish) {
        //1.创建查询对象
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();

        //2.设置查询条件，根据菜品分类id查询或者根据菜品名称查询
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        wrapper.like(dish.getName() != null, Dish::getName, dish.getName());

        //3.调用service的查询方法list
        List<Dish> dishes = dishService.list(wrapper);

        //4.返回结果给前端
        return R.success(dishes);
    }*/

    /**
     * 查询菜品列表数据包含口味信息
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> listWithFlavors(Dish dish){
        //1.调用service的查询列表方法
        List<DishDto> dishDtos = dishService.listWithFlavors(dish);
        //2.返回结果
        return R.success(dishDtos);
    }

    /**
     * 菜品删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> removeDish(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getStatus,0);
        int count = dishService.count(lqw);
        if (count != ids.size()){
            return R.error("删除失败,有菜品为启售状态");
        }
        
        LambdaQueryWrapper<SetmealDish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.in(SetmealDish::getDishId,ids);
        int count1 = setmealDishService.count(lqw1);
        if (count1 > 0){
            return R.error("删除失败,有套餐包含此套餐");
        }
        

        return dishService.removeByIds(ids) ? R.success("") : R.error("菜品删除失败");
    }

    /**
     * 菜品状态更新
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@RequestParam List<Long> ids,@PathVariable Integer status){
        LambdaUpdateWrapper<Dish> luw = new LambdaUpdateWrapper();
        luw.in(Dish::getId,ids);
        luw.set(Dish::getStatus,status);
        return dishService.update(luw) ? R.success("") : R.error("状态更新失败");
    }
}
